> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/jaypopat/cf_ai_duet/llms.txt
> Use this file to discover all available pages before exploring further.

# Room Manager

> Multi-user room and workspace management

## Overview

The `room` package provides room management functionality for collaborative sessions, including workspace isolation, client connections, and resource cleanup.

## Types

### Manager

Manages all active rooms and their lifecycle.

```go theme={null}
type Manager struct {
    rooms     map[string]*Room
    mu        sync.RWMutex
    workerURL string
    aiClient  *ai.Client
    logger    *log.Logger
}
```

### Room

Represents a collaborative session with shared terminal and AI chat.

```go theme={null}
type Room struct {
    ID           string
    Description  string
    Host         string
    Connections  []*Client
    Terminal     *terminal.Terminal
    AIMessages   []AIMessage
    WorkspaceDir string
}
```

### Client

Represents a connected user in a room.

```go theme={null}
type Client struct {
    ID       string
    Username string
    IsHost   bool
    Events   chan RoomEvent
}
```

### RoomEvent

Events broadcast to room participants.

```go theme={null}
type RoomEvent struct {
    Type     string    // "join", "leave", "typing", "ai_sync"
    Username string
    Data     string
}
```

### AIMessage

AI chat message stored in room history.

```go theme={null}
type AIMessage struct {
    Role   string `json:"role"`
    UserID string `json:"user_id"`
    Text   string `json:"text"`
    Ts     int64  `json:"ts"`
}
```

## Manager Functions

### NewManager

Creates a new room manager instance.

```go theme={null}
func NewManager(workerURL string, aiClient *ai.Client, logger *log.Logger) *Manager
```

<ParamField path="workerURL" type="string">
  URL for the AI worker service (empty string disables AI features)
</ParamField>

<ParamField path="aiClient" type="*ai.Client">
  Shared AI client for all rooms
</ParamField>

<ParamField path="logger" type="*log.Logger">
  Logger instance for room events
</ParamField>

### CreateRoom

Creates a new collaborative room with isolated workspace.

```go theme={null}
func (m *Manager) CreateRoom(host, description string) (*Room, error)
```

<ParamField path="host" type="string" required>
  Username of the room host
</ParamField>

<ParamField path="description" type="string">
  Room description (used to generate workspace name)
</ParamField>

**Returns:**

* `*Room`: The created room with unique ID
* `error`: If workspace creation fails

**Workspace Naming:**

* Slugified description if provided (e.g., "my project" → "my-project")
* Random readable name if empty (e.g., "swift-phoenix", "cosmic-dragon")
* Max 30 characters

**Example:**

```go theme={null}
room, err := manager.CreateRoom("alice", "React Dashboard")
if err != nil {
    return err
}
fmt.Println("Room ID:", room.ID)
fmt.Println("Workspace:", room.WorkspaceDir)
```

### GetRoom

Retrieves an existing room by ID.

```go theme={null}
func (m *Manager) GetRoom(roomID string) (*Room, error)
```

<ParamField path="roomID" type="string" required>
  Unique room identifier
</ParamField>

**Returns:**

* `*Room`: The requested room
* `error`: `ErrRoomNotFound` if room doesn't exist

### LeaveRoom

Removes a client from a room and cleans up if empty.

```go theme={null}
func (m *Manager) LeaveRoom(roomID, clientID string) bool
```

<ParamField path="roomID" type="string" required>
  Room to leave
</ParamField>

<ParamField path="clientID" type="string" required>
  Client identifier
</ParamField>

**Returns:** `true` if the room was destroyed (last client left)

**Cleanup Actions:**

* Closes terminal if exists
* Removes workspace directory
* Calls worker API to cleanup sandbox resources
* Deletes room from manager

### GetAIClient

Retrieves the shared AI client.

```go theme={null}
func (m *Manager) GetAIClient() *ai.Client
```

**Returns:** The AI client instance (may be nil)

### RoomCount

Returns the number of active rooms.

```go theme={null}
func (m *Manager) RoomCount() int
```

## Room Methods

### AddClient

Adds a client to the room and broadcasts join event.

```go theme={null}
func (r *Room) AddClient(client *Client)
```

<ParamField path="client" type="*Client" required>
  Client to add (replaces existing client with same ID)
</ParamField>

### RemoveClient

Removes a client and broadcasts leave event.

```go theme={null}
func (r *Room) RemoveClient(clientID string)
```

### BroadcastEvent

Sends an event to all clients except one.

```go theme={null}
func (r *Room) BroadcastEvent(event RoomEvent, excludeClientID string)
```

<ParamField path="event" type="RoomEvent" required>
  Event to broadcast
</ParamField>

<ParamField path="excludeClientID" type="string">
  Client ID to exclude (typically the sender)
</ParamField>

### GetClients

Returns a copy of all connected clients.

```go theme={null}
func (r *Room) GetClients() []*Client
```

### ClientCount

Returns the number of connected clients.

```go theme={null}
func (r *Room) ClientCount() int
```

### SetAIMessages / GetAIMessages

Thread-safe AI message history management.

```go theme={null}
func (r *Room) SetAIMessages(msgs []AIMessage)
func (r *Room) GetAIMessages() []AIMessage
```

## Errors

```go theme={null}
var ErrRoomNotFound = errors.New("room not found")
```

## Workspace Isolation

Each room gets an isolated workspace directory:

1. **Production**: Copies `/app/workspace-template/` to `/app/workspaces/{name}/`
2. **Development**: Creates empty directory in temp folder

This provides filesystem isolation for each collaborative session.
